package groupb6.shopsystem.messaging.entity;

import com.fasterxml.jackson.databind.ObjectMapper;
import groupb6.shopsystem.messaging.server.WebsocketServer;
import groupb6.shopsystem.pojo.entity.Message;
import groupb6.shopsystem.pojo.entity.User;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


/*
 * 群组聊天功能实现
 * @Author zhangyn
 * */
@Data
@Slf4j
@NoArgsConstructor
public class WebSocketGroup {
    /*
     * json解析类
     * */
    private static ObjectMapper jsonParser = new ObjectMapper();
    /**
     * 用来记录当前聊天室在线连接数。线程安全
     */
    private AtomicInteger onlineNum = new AtomicInteger();
    /*
     * 当前聊天下的连接集合
     * */
    private Map<Integer, Session> sessionMap = new ConcurrentHashMap<>();
    /*
     * 聊天群组属性
     * */
    //卖家
    private User seller;
    //买家
    private User customer;
    //管理员
    private User admin;
    //历史聊天消息
    private List<Message> historyMessages;
    //聊天消息
    private List<Message> newMessages;
    //卖家是否在线
//    private boolean sellerIsPresent = false;
//    //买家是否在线
//    private boolean customerIsPresent = false;
//    //Admin是否在线
//    private boolean adminIsPresent = false;
    //key
    private Key key;
    //错误信息
    private String errMsg;


    public void addUser(User user, Session session) {
        addOnlineCount();
        for (Integer id : sessionMap.keySet()) {
            if (id.equals(user.getId())) {
                log.info(user.getName() + "尝试重复加入，已拒绝");
                throw new RuntimeException("同一user无法重复加入！");
            }
        }
        sessionMap.put(user.getId(), session);
    }

    public void exitUser(User user, Session session) {
        subOnlineCount();
        try {
            sessionMap.remove(user.getId(), session);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("group删除对象失败");
        }

    }

    /**
     * 增加在线用户数量
     */
    public void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    /**
     * 删除在线用户数量
     */
    public void subOnlineCount() {
        onlineNum.decrementAndGet();
    }


    /**
     * 发送状态
     */
    public void postStatus(User user, String status) {
        sendStatus(sessionMap.get(user.getId()), status);
    }

    public void postStatusAll(String status) {
        for (Session session : sessionMap.values()) {
            sendStatus(session, status);
        }
    }

    /**
     * 发送消息
     */
    public void postMessage(User user, Message message) {
        List<Message> messages = new ArrayList<>();
        messages.add(message);
        sendMessage(sessionMap.get(user.getId()), messages);
    }

    public void postMessageAll(Message message) {
        List<Message> messages = new ArrayList<>();
        messages.add(message);
        for (Session session : sessionMap.values()) {
            sendMessage(session, messages);
        }
    }

    /*
     * 发送历史记录
     * */
    public void loadMessage(User user) {
        sendMessage(sessionMap.get(user.getId()), historyMessages);
        sendMessage(sessionMap.get(user.getId()), newMessages);
    }


    /**
     * 封装两个send方法，发送消息到前端
     */
    private void sendMessage(Session session, List<Message> messages) {
        try {
            WBResponse response = new WBResponse();
            response.setType("message");
            response.setMessages(messages);

            String json = jsonParser.writeValueAsString(response);
            System.out.println(json);
            session.getBasicRemote().sendText(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendStatus(Session session, String status) {
        try {
            WBResponse response = new WBResponse();
            response.setType("status");
            response.setStatus(status);

            String json = jsonParser.writeValueAsString(response);
            System.out.println(json);
            session.getBasicRemote().sendText(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
